class Solution {
public:
    vector<int> findOrder(int n, vector<vector<int>>& p) {
        unordered_map<int,vector<int>> um;
        vector<int> v(n);
        vector<int> ret;
        vector<int> a;

        for(auto& e:p)
        {
            int a=e[0];
            int b=e[1];
            v[a]++;
            um[b].push_back(a);
        }
        queue<int> q;
        for(int i=0;i<n;++i)
        {
            if(v[i]==0)
            {
                q.push(i);
            }
        }

        while(q.size())
        {
            int t=q.front();
            q.pop();
            ret.push_back(t);
            for(auto ch:um[t])
            {
                v[ch]--;
                if(v[ch]==0)
                {
                    q.push(ch);
                }
            }
        }
        for(int i=0;i<n;++i)
        {
            if(v[i]) return a;
        }
        return ret;
    }
};
